#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <unistd.h>
#include "LockGuard.hpp"

#define NUM 5
using namespace std;

int tickets = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;  //同一把锁
// pthread_mutex_t mutex;

void *ThreadRoutine(void *args)
{
    int i = (uint64_t)args;
    while(true)
    {  
        {   //使用代码块标识临界区
            // pthread_mutex_lock(&mutex);
            LockGuard Mutex(&lock);
            if(tickets > 0)
            {
                //usleep(1000);
                printf("who=thread->%d get a ticket: %d\n", i, tickets);
                tickets--;
            //pthread_mutex_unlock(&mutex);
            }
            else
            {
            //pthread_mutex_unlock(&mutex);

                break;
            }
            usleep(1000);
            // pthread_mutex_unlock(&mutex);
        }
    }
    pthread_exit((void*)666);
}

int main()
{
    //初始化锁，如果将锁的初始化放在例程中，那么当线程去执行代码时，就会不断的初始化锁，这样每个线程可以申请到锁，这样锁就没意义了
    // pthread_mutex_init(&mutex, nullptr); 

    pthread_t tid;
    vector<pthread_t> tids;
    for(int i = 0; i < NUM; i++)
    {
        pthread_create(&tid, nullptr, ThreadRoutine, (void*)i);
        tids.push_back(tid);
    }

    for(int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    // pthread_mutex_destroy(&mutex);

    return 0;
}

